import { ExtraFields } from '@/constants/extra-fields';
import { fieldConfig2TreeData } from '@/utils';
import { Tree, TreeDataNode } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import React, { useMemo } from 'react';
import { useModel } from 'umi';

const extraFieldsTreeData: TreeDataNode[] = [
  {
    title: '主键',
    key: ExtraFields.MainFieldId,
  },
  {
    title: '更新时间',
    key: ExtraFields.UpdateTime,
  },
];

export const FieldConfig: React.FC<{
  className?: string;
  onSelect?(id: string): void;
}> = (props) => {
  const { fieldConfig, exportedFields, setExportedFields } =
    useModel('fieldConfig');
  const treeData = useMemo(
    () => [
      ...extraFieldsTreeData,
      ...(fieldConfig ? fieldConfig2TreeData(fieldConfig) : []),
    ],
    [fieldConfig],
  );

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
    props.onSelect?.((checkedKeys as string[])[0]);
    setExportedFields(checkedKeys as string[]);
  };
  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    console.log('onSelect', selectedKeys, info);
    props.onSelect?.((selectedKeys as string[])[0]);
    setExportedFields(selectedKeys as string[]);
  };

  return (
    <Tree
      // checkable
      autoExpandParent
      // defaultCheckedKeys={exportedFields}
      // onCheck={onCheck}
      onSelect={onSelect}
      treeData={treeData}
      className={props.className}
    />
  );
};
